import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';
import Toast from '@vant/weapp/toast/toast';
Page({
  data: {
    defaultData: {
      title: "钱包充值", // 导航栏标题
      imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },
    moneyList: [{
        id: 0,
        money: 500,
        moneyGive: 50
      },
      {
        id: 1,
        money: 1000,
        moneyGive: 100
      },
      {
        id: 2,
        money: 2000,
        moneyGive: 200
      },
      {
        id: 3,
        money: 3000,
        moneyGive: 300
      },
      {
        id: 4,
        money: 5000,
        moneyGive: 500
      },
      {
        id: 5,
        money: 10000,
        moneyGive: 1000
      },

    ],
    checked: true,
    selectedId: null,
    selectedMoney: 1000,
    selectedMoneyGive: null,
  },

  // 选择金额
  selectItem(e) {
    const selectedId = e.currentTarget.dataset.id;
    const selectedItem = this.data.moneyList.find(item => item.id === selectedId);
    this.setData({
      selectedId,
      selectedMoney: selectedItem.money,
      selectedMoneyGive: selectedItem.moneyGive
    });
    console.log("selectedMoney", this.data.selectedMoney);
  },

  // 充值
  async clickRecharge() {
    const reqTemplate = {
      total: this.data.selectedMoney
    }
    if (this.data.checked == false) {
      Toast('请选择微信支付');
      return;
    }else{
      try {
        const res = await request({
          url: indexApi.rechargeMoneyApi(),
          method: "POST",
          data: reqTemplate
        });
        console.log(res);
        this.requestPayment(res.data)
      } catch (error) {
        console.error("Error:", error);
      
      }
    }
    
  },

  requestPayment(data) {
    const that = this;
    return new Promise((resolve, reject) => {
      wx.requestPayment({
        timeStamp: data.timeStamp, // 支付签名时间戳
        nonceStr: data.nonceStr, // 支付签名随机串
        package: data.packageStr, // 统一支付接口返回的 prepay_id 参数值
        signType: data.signType, // 签名算法，暂支持 MD5
        paySign: data.paySign, // 签名
        success(res) {
          console.log('支付成功');
          // 支付成功
          resolve(res);
          that.updateUserMoney()      
          Toast('您已取消支付');
        },
        fail(err) {
          // 支付失败
          reject(err);
          Toast('支付失败');
        },
        complete() {
          // 支付结果处理完成
        },
      });
    })
  },

  async updateUserMoney() {
    const reqTemplate = {
      total: this.data.selectedMoney
    }
    try {
      const res = await request({
        url: indexApi.updateUserMoneyApi(),
        method: "POST",
        data: reqTemplate
      });
      wx.switchTab({
        url: '/pages/usercenter/index',
      })
      console.log("更新账户余额", res.data);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  onChange(event) {
    this.setData({
      checked: event.detail,
    });
  },

  onShareAppMessage() {
    return {};
  },
});